﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ImageSpliter
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private uint vCount = 1;
        private uint hCount = 1;

        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 根据文件扩展名获取图片编码器
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>图片编码器</returns>
        private BitmapEncoder GetBitmapEncoder(string filePath)
        {
            var extName = System.IO.Path.GetExtension(filePath).ToLower();
            if (extName.Equals(".png"))
            {
                return new PngBitmapEncoder();
            }
            else
            {
                return new JpegBitmapEncoder();
            }
        }

        private void textBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //打开文件选择器
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "图像文件(*.jpg; *.jpeg; *.png)| *.jpg; *.jpeg; *.png";
            if (dialog.ShowDialog() == true)
            {
                string file = dialog.FileName;
                textBox.Text = file;
                textBox.Foreground = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
            }

            //判断文件是否存在
            if (!File.Exists(textBox.Text))
            {
                return;
            }
            //加载并显示
            var st = new FileStream(textBox.Text, FileMode.Open);
            var d = new PngBitmapDecoder(st, BitmapCreateOptions.None, BitmapCacheOption.None);
            image.Source = d.Frames[0];
        }
        //输入文本
        private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            trySetCount(textBox1);
        }

        private void textBox2_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            trySetCount(textBox2);
        }

        private void trySetCount(TextBox _textbox)
        {
            try
            {
                var newNum = uint.Parse(_textbox.Text);
            }
            catch (Exception)
            {
                _textbox.Text = vCount.ToString();
                return;
            }
        }

        private void textBox3_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = dialog.SelectedPath;
                textBox3.Text = path;
                textBox3.Foreground = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
            }

        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            Console.Write("按钮点击");
            var bitMap = image.Source as BitmapFrame;
            if (bitMap == null) {
                MessageBox.Show("没有有效的图片资源");
                return;
            }
            var _idx = textBox.Text.LastIndexOf(@"\");
            _idx = _idx == -1 ? 0 : _idx;
            var orgFileName = textBox.Text.Substring(_idx + 1);
            var suffix = orgFileName.Substring(orgFileName.Length - 4);
            orgFileName = orgFileName.Substring(0, orgFileName.Length - 4);
            var orgPath = textBox.Text.Substring(0, _idx + 1);
            //切分单位
            var hCount = int.Parse(textBox1.Text);
            hCount = hCount > bitMap.PixelWidth ? bitMap.PixelWidth : hCount;
            var vCount = int.Parse(textBox2.Text);
            vCount = vCount > bitMap.PixelHeight ? bitMap.PixelHeight : vCount;
            int unitW = bitMap.PixelWidth / hCount;
            int unitH = bitMap.PixelHeight / vCount;

            var unitSize = bitMap.Format.BitsPerPixel / 8;
            var data = new int[unitW * unitH * unitSize];
            var stride = unitSize * unitW;
            var outPath = textBox3.Text;
            if (!Directory.Exists(outPath))
            {
                outPath = orgPath;
                MessageBox.Show("输出目录错误");
                if (Directory.Exists(outPath))
                {
                    MessageBox.Show("没有正确的输出路径");
                    return;
                }
            }

            for (int y = 0; y < vCount; y++)
            {
                for (int x = 0; x < hCount; x++)
                {
                    //切分像素
                    var rect = new Int32Rect(x * unitW, y * unitH, unitW, unitH);
                    bitMap.CopyPixels(rect, data, stride, 0);
                    var newBitMap = BitmapSource.Create(rect.Width, rect.Height, 0, 0, PixelFormats.Bgra32, null, data, stride);
                    //image.Source = newBitMap;

                    //持久化
                    var fileName = string.Format("{0}_{1}_{2}{3}", orgFileName, x, y, suffix);
                    var outFile = string.Format("{0}/{1}", textBox3.Text, fileName);
                    var encoder = GetBitmapEncoder(outFile);
                    encoder.Frames.Add(BitmapFrame.Create(newBitMap));
                    using (var st = new FileStream(outFile, FileMode.Create))
                    {
                        encoder.Save(st);
                    }
                }
            }

            MessageBox.Show("切分完毕！");

        }

    }
}
